<template>
  <div>
    <el-form label-width="90px" :model="formState" :rules="rules" ref="formRef">
      <el-form-item label="姓名" prop="realname">
        <el-input v-model="formState.realname">  </el-input>
      </el-form-item>
      <el-form-item label="账号">
        <el-input readonly v-model="formState.username" />
      </el-form-item>
      <el-form-item label="修改密码">
        <el-checkbox v-model="isPassword"> </el-checkbox>
      </el-form-item>
      <el-form-item v-if="isPassword" label="密码" prop="password">
        <el-input v-model="formState.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm"> 保存</el-button>
        <el-button type="primary" @click="resetForm"> 清空 </el-button>
      </el-form-item>
      <el-form-item>
       
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue";
import { dayjs } from "element-plus";
import type { FormInstance, CascaderOption } from "element-plus";
import type { IAddUserFormType } from "@/typings/ladyType";
import {useEditValidate} from "../useValidate";
import {getUserIdToInfoApi,editUserApi} from "@/api/ladyApi";
import { Row } from "element-plus/es/components/table-v2/src/components";
import { rowContextKey } from "element-plus";

interface IProps {
  setVisible: (v: boolean) => void;
  userid: number;
  aaa:any
 
}
const props = defineProps<IProps>();
 
const formRef = ref<FormInstance>();
const rules = useEditValidate();
// 是否修改密码
const isPassword = ref(false);

let formState = reactive<Optional<IAddUserFormType, "password">>({
  username: "",
  password: '111',
  sex: "1",
  age: 1,
  region: ["aa", "bb"],
  avatar: "http:xxx.com",
  realname: "",
  cdate: dayjs().add(-20, "y").format("YYYY-MM-DD"),
  phone:'',
  wechat:''
});

watch(isPassword, (v) => {
  if (!v) {
    formState.password = undefined;
  }
});

onMounted(async () => {
  let ret = await getUserIdToInfoApi(props.userid);
  console.log(ret,'回显的mock数据')
  
  let state: Partial<typeof ret.data> & { password?: string } = ret.data;
  delete state.id;
  for (let key in formState) {
    // ;(formState as any)[key] = (state as any)[key]
    // unknown它是有类型检查，在使用时要指定类型
    (formState[key as keyof IAddUserFormType] as unknown) =
      state[key as keyof typeof state];
  }
});


const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid: boolean) => {
    // 表单项验证通过
    if (valid) {
      // 1.请求
      // 2.响应，成功|失败
      // 3.关闭当前弹出层
      // 4.请求1次
      let ret = await editUserApi(props.userid, formState)
      console.log(ret,'修改之后的数据')
      if (ret.code === 0) {
        props.setVisible(false)
      }
    } else {
      return false
    }
  })
}
// 重置表单
const resetForm=()=>{
  formState.realname='',
  formState.username='',
  formState.password=''
}
</script>

<style lang="scss" scoped></style>
